import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
from datetime import datetime

class PasswordDialog:
    def __init__(self, parent):
        print("PasswordDialog初始化")
        self.parent = parent
        self.result = None
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("密码验证")
        self.dialog.geometry("350x150")
        self.dialog.resizable(False, False)
        self.dialog.transient(parent)  # 设置为主窗口的子窗口
        self.dialog.grab_set()  # 模态窗口
        
        # 设置淡绿色主题样式
        style = ttk.Style()
        style.theme_use('clam')
        
        # 设置颜色方案
        primary_color = '#1b5e20'  # 主色调-深绿色
        primary_dark = '#0d47a1'   # 更深的绿色
        text_color = '#202124'     # 主文本色
        bg_color = '#ffffff'       # 背景色
        border_color = '#a5d6a7'   # 边框色-浅深绿色
        
        # 标签样式 - 移除背景颜色设置，使其透明
        style.configure('TLabel', font=('微软雅黑', 10), foreground=text_color)
        
        # 按钮样式
        style.configure('TButton', font=('微软雅黑', 10))
        style.configure('Primary.TButton', font=('微软雅黑', 10), foreground='white', background=primary_color)
        style.map('Primary.TButton', background=[('active', primary_dark)])
        
        # 框架样式
        style.configure('Card.TFrame', background=bg_color, borderwidth=1, relief='solid', bordercolor=border_color)
        
        # 输入框样式
        style.configure('TEntry', font=('微软雅黑', 10), padding=3, borderwidth=1, bordercolor=border_color)
        
        # 居中显示
        self.center_window(self.dialog)
        
        # 创建密码对话框
        self.create_dialog_ui()
        
        # 确保窗口可见
        self.dialog.update_idletasks()
        self.dialog.lift()
        
    def center_window(self, window):
        window.update_idletasks()
        width = window.winfo_width()
        height = window.winfo_height()
        x = (window.winfo_screenwidth() // 2) - (width // 2)
        y = (window.winfo_screenheight() // 2) - (height // 2)
        window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
        
    def create_dialog_ui(self):# 主框架
        frame = ttk.LabelFrame(self.dialog, padding="20", style='Card.TFrame')
        frame.pack(fill=tk.BOTH, expand=True)
        
        # 提示信息
        ttk.Label(frame, text="请输入密码以验证身份:", font=("微软雅黑", 10)).pack(pady=(0, 10))
        
        # 密码输入
        password_frame = ttk.Frame(frame)
        password_frame.pack(fill=tk.X, pady=5)
        ttk.Label(password_frame, text="密      码:", width=10).pack(side=tk.LEFT, padx=5)
        self.password_entry = ttk.Entry(password_frame, show="*")
        self.password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)
        
        # 按钮
        button_frame = ttk.Frame(frame)
        button_frame.pack(pady=10)
        ttk.Button(button_frame, text="确认", command=self.confirm, style='Primary.TButton').pack(side=tk.LEFT, padx=10)
        ttk.Button(button_frame, text="取消", command=self.cancel).pack(side=tk.LEFT, padx=10)
        
    def confirm(self):
        password = self.password_entry.get()
        
        # 简单验证逻辑，与数据库中的管理员密码进行比较
        if self.verify_admin_password(password):
            self.result = password
            self.dialog.destroy()
        else:
            messagebox.showerror("错误", "密码不正确！")
            self.password_entry.delete(0, tk.END)
            
    def verify_admin_password(self, password):
        try:
            conn = sqlite3.connect('water_electricity.db')
            cursor = conn.cursor()
            # 检查是否是管理员密码
            cursor.execute("SELECT * FROM users WHERE username='admin' AND password=?", (password,))
            result = cursor.fetchone()
            conn.close()
            return result is not None
        except Exception as e:
            messagebox.showerror("错误", f"数据库错误: {str(e)}")
            return False
            
    def cancel(self):
        self.result = None
        self.dialog.destroy()

class LoginUI:
    def __init__(self, root, on_login_success):
        self.root = root
        self.on_login_success = on_login_success
        self.current_user = None
        self.setup_login_ui()
    
    def setup_login_ui(self):
        # 创建登录界面
        self.login_window = tk.Toplevel(self.root)
        self.login_window.title("用户登录")
        # 先隐藏窗口，防止闪烁
        self.login_window.withdraw()
        
        # 设置窗口大小和不可调整
        self.login_window.geometry("400x350")
        self.login_window.resizable(False, False)
        self.login_window.protocol("WM_DELETE_WINDOW", self.on_close)
        
        # 居中显示的改进方法
        self.login_window.update_idletasks()  # 确保窗口尺寸已计算
        width = self.login_window.winfo_width()
        height = self.login_window.winfo_height()
        x = (self.login_window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.login_window.winfo_screenheight() // 2) - (height // 2)
        self.login_window.geometry(f"{width}x{height}+{x}+{y}")
        
        # 窗口准备好后再显示
        self.login_window.deiconify()
        
        # 窗口显示后，设置密码输入框自动获取焦点
        self.login_window.after(100, lambda: self.password_entry.focus_set())
        
        # 设置样式 - 淡绿色主题
        style = ttk.Style()
        style.theme_use('clam')
        
        # 设置颜色方案
        primary_color = '#1b5e20'  # 主色调-深绿色
        primary_dark = '#0d47a1'   # 更深的绿色
        primary_light = '#c8e6c9'  # 浅深绿色
        text_color = '#202124'     # 主文本色
        bg_color = '#ffffff'       # 背景色
        border_color = '#a5d6a7'   # 边框色-浅深绿色
        
        # 标签样式 - 移除背景颜色设置，使其透明
        style.configure('TLabel', font=('微软雅黑', 12), foreground=text_color)
        
        # 按钮样式
        style.configure('TButton', font=('微软雅黑', 12))
        style.configure('Primary.TButton', font=('微软雅黑', 12), foreground='white', background=primary_color)
        style.map('Primary.TButton', background=[('active', primary_dark)])
        
        # 框架样式
        style.configure('Card.TFrame', background=bg_color, borderwidth=1, relief='solid', bordercolor=border_color)
        
        # 输入框样式
        style.configure('TEntry', font=('微软雅黑', 12), padding=3, borderwidth=1, bordercolor=border_color)
        
        # 主框架
        main_frame = ttk.LabelFrame(self.login_window, padding=30, style='Card.TFrame')
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="用户登录", font=('微软雅黑', 16, 'bold'))
        title_label.pack(pady=(0, 20))
        
        # 用户名
        username_frame = ttk.Frame(main_frame)
        username_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(username_frame, text="用户名：").pack(side=tk.LEFT, padx=(0, 10))
        self.username_entry = ttk.Entry(username_frame, font=('微软雅黑', 12), width=20)
        self.username_entry.insert(0, "admin")  # 设置默认用户名为"admin"
        self.username_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 密码
        password_frame = ttk.Frame(main_frame)
        password_frame.pack(fill=tk.X, pady=(0, 20))
        
        ttk.Label(password_frame, text="密   码：").pack(side=tk.LEFT, padx=(0, 10))
        self.password_entry = ttk.Entry(password_frame, font=('微软雅黑', 12), width=20, show="*")
        self.password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 添加回车键绑定，按下回车时触发登录按钮事件
        self.password_entry.bind("<Return>", lambda event: self.login())
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.login_button = ttk.Button(button_frame, text="登录", command=self.login, style='Primary.TButton')
        self.login_button.pack(side=tk.LEFT, padx=(0, 10), fill=tk.X, expand=True)
        
        self.register_button = ttk.Button(button_frame, text="注册", command=self.setup_register_ui)
        self.register_button.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 修改密码按钮
        change_password_frame = ttk.Frame(main_frame)
        change_password_frame.pack(fill=tk.X)
        
        self.change_password_button = ttk.Button(change_password_frame, text="修改管理员密码", command=self.setup_change_password_ui)
        self.change_password_button.pack(fill=tk.X)
    
    def setup_register_ui(self):
        # 隐藏登录窗口，显示注册窗口
        self.login_window.withdraw()
        
        self.register_window = tk.Toplevel(self.root)
        self.register_window.title("用户注册")
        # 先隐藏窗口，防止闪烁
        self.register_window.withdraw()
        
        # 设置窗口大小和不可调整
        self.register_window.geometry("400x350")
        self.register_window.resizable(False, False)
        self.register_window.protocol("WM_DELETE_WINDOW", self.back_to_login)
        
        # 居中显示的改进方法
        self.register_window.update_idletasks()  # 确保窗口尺寸已计算
        width = self.register_window.winfo_width()
        height = self.register_window.winfo_height()
        x = (self.register_window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.register_window.winfo_screenheight() // 2) - (height // 2)
        self.register_window.geometry(f"{width}x{height}+{x}+{y}")
        
        # 设置深绿色主题样式（与登录界面保持一致）
        style = ttk.Style()
        style.theme_use('clam')
        
        # 设置颜色方案
        primary_color = '#1b5e20'  # 主色调-深绿色
        primary_dark = '#0d47a1'   # 更深的绿色
        text_color = '#202124'     # 主文本色
        bg_color = '#ffffff'       # 背景色
        border_color = '#a5d6a7'   # 边框色-浅深绿色
        
        # 标签样式 - 移除背景颜色设置，使其透明
        style.configure('TLabel', font=('微软雅黑', 12), foreground=text_color)
        
        # 按钮样式
        style.configure('TButton', font=('微软雅黑', 12))
        style.configure('Primary.TButton', font=('微软雅黑', 12), foreground='white', background=primary_color)
        style.map('Primary.TButton', background=[('active', primary_dark)])
        
        # 框架样式
        style.configure('Card.TFrame', background=bg_color, borderwidth=1, relief='solid', bordercolor=border_color)
        
        # 输入框样式
        style.configure('TEntry', font=('微软雅黑', 12), padding=3, borderwidth=1, bordercolor=border_color)
        
        # 窗口准备好后再显示
        self.register_window.deiconify()
        
        # 主框架
        main_frame = ttk.LabelFrame(self.register_window, padding=30, style='Card.TFrame')
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="用户注册", font=('微软雅黑', 16, 'bold'))
        title_label.pack(pady=(0, 20))
        
        # 用户名
        username_frame = ttk.Frame(main_frame)
        username_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(username_frame, text="用 户  名：").pack(side=tk.LEFT, padx=(0, 10))
        self.register_username_entry = ttk.Entry(username_frame, font=('微软雅黑', 12), width=20)
        self.register_username_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 密码
        password_frame = ttk.Frame(main_frame)
        password_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(password_frame, text="密      码：").pack(side=tk.LEFT, padx=(0, 10))
        self.register_password_entry = ttk.Entry(password_frame, font=('微软雅黑', 12), width=20, show="*")
        self.register_password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 确认密码
        confirm_frame = ttk.Frame(main_frame)
        confirm_frame.pack(fill=tk.X, pady=(0, 20))
        
        ttk.Label(confirm_frame, text="确认密码：").pack(side=tk.LEFT, padx=(0, 10))
        self.confirm_password_entry = ttk.Entry(confirm_frame, font=('微软雅黑', 12), width=20, show="*")
        self.confirm_password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.register_submit_button = ttk.Button(button_frame, text="注册", command=self.register, style='Primary.TButton')
        self.register_submit_button.pack(side=tk.LEFT, padx=(0, 10), fill=tk.X, expand=True)
        
        self.back_button = ttk.Button(button_frame, text="返回", command=self.back_to_login)
        self.back_button.pack(side=tk.LEFT, fill=tk.X, expand=True)
    
    def back_to_login(self):
        # 关闭注册窗口，显示登录窗口
        if hasattr(self, 'register_window'):
            self.register_window.destroy()
        self.login_window.deiconify()
    
    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        
        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码！")
            return
        
        # 验证用户
        if self.verify_user(username, password):
            self.current_user = username
            self.login_window.destroy()
            # messagebox.showinfo("成功", f"欢迎{username}！进入吾已水电费管理系统！")
            self.on_login_success()
        else:
            messagebox.showerror("错误", "用户名或密码错误！")
    
    def register(self):
        username = self.register_username_entry.get().strip()
        password = self.register_password_entry.get().strip()
        confirm_password = self.confirm_password_entry.get().strip()
        
        # 验证输入
        if not username or not password:
            messagebox.showerror("错误", "用户名和密码不能为空！")
            return
        
        if password != confirm_password:
            messagebox.showerror("错误", "两次输入的密码不一致！")
            return
        
        # 注册用户
        if self.add_user(username, password):
            messagebox.showinfo("成功", "用户注册成功！请登录。")
            self.back_to_login()
        else:
            messagebox.showerror("错误", "用户名已存在！")
    
    def verify_user(self, username, password):
        # 连接数据库验证用户
        try:
            conn = sqlite3.connect('water_electricity.db')
            cursor = conn.cursor()
            cursor.execute("SELECT password FROM users WHERE username=?", (username,))
            result = cursor.fetchone()
            conn.close()
            
            # 注意：实际应用中应使用哈希函数验证密码
            return result and result[0] == password
        except Exception as e:
            messagebox.showerror("错误", f"数据库错误：{str(e)}")
            return False
    
    def add_user(self, username, password):
        # 添加新用户到数据库
        try:
            conn = sqlite3.connect('water_electricity.db')
            cursor = conn.cursor()
            
            # 检查用户是否已存在
            cursor.execute("SELECT id FROM users WHERE username=?", (username,))
            if cursor.fetchone():
                conn.close()
                return False
            
            # 插入新用户
            # 注意：实际应用中应使用哈希函数加密密码
            cursor.execute(
                "INSERT INTO users (username, password) VALUES (?, ?)",
                (username, password)
            )
            
            conn.commit()
            conn.close()
            return True
        except Exception as e:
            messagebox.showerror("错误", f"数据库错误：{str(e)}")
            return False
    
    def on_close(self):
        # 关闭登录窗口时退出应用
        self.root.destroy()
    
    def verify_password(self, username, password):
        # 验证密码（用于二次验证）
        return self.verify_user(username, password)
    
    def get_current_user(self):
        # 获取当前登录用户
        return self.current_user

    def setup_change_password_ui(self):
        # 创建修改密码界面
        self.change_password_window = tk.Toplevel(self.root)
        self.change_password_window.title("修改密码")
        self.change_password_window.geometry("400x350")
        self.change_password_window.resizable(False, False)
        
        # 居中显示
        self.change_password_window.update_idletasks()
        width = self.change_password_window.winfo_width()
        height = self.change_password_window.winfo_height()
        x = (self.change_password_window.winfo_screenwidth() // 2) - (width // 2)
        y = (self.change_password_window.winfo_screenheight() // 2) - (height // 2)
        self.change_password_window.geometry(f"{width}x{height}+{x}+{y}")
        
        # 设置深绿色主题样式（与登录界面保持一致）
        style = ttk.Style()
        style.theme_use('clam')
        
        # 设置颜色方案
        primary_color = '#1b5e20'  # 主色调-深绿色
        primary_dark = '#0d47a1'   # 更深的绿色
        text_color = '#202124'     # 主文本色
        bg_color = '#ffffff'       # 背景色
        border_color = '#a5d6a7'   # 边框色-浅深绿色
        
        # 标签样式 - 移除背景颜色设置，使其透明
        style.configure('TLabel', font=('微软雅黑', 12), foreground=text_color)
        
        # 主框架
        main_frame = ttk.LabelFrame(self.change_password_window, padding=30, style='Card.TFrame')
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="修改密码", font=('微软雅黑', 16, 'bold'))
        title_label.pack(pady=(0, 20))
        
        # 旧密码
        old_password_frame = ttk.Frame(main_frame)
        old_password_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(old_password_frame, text="旧 密 码：").pack(side=tk.LEFT, padx=(0, 10))
        self.old_password_entry = ttk.Entry(old_password_frame, font=('微软雅黑', 12), width=20, show="*")
        self.old_password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 新密码
        new_password_frame = ttk.Frame(main_frame)
        new_password_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(new_password_frame, text="新 密 码：").pack(side=tk.LEFT, padx=(0, 10))
        self.new_password_entry = ttk.Entry(new_password_frame, font=('微软雅黑', 12), width=20, show="*")
        self.new_password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 确认新密码
        confirm_password_frame = ttk.Frame(main_frame)
        confirm_password_frame.pack(fill=tk.X, pady=(0, 20))
        
        ttk.Label(confirm_password_frame, text="确认新密码：").pack(side=tk.LEFT, padx=(0, 10))
        self.confirm_new_password_entry = ttk.Entry(confirm_password_frame, font=('微软雅黑', 12), width=20, show="*")
        self.confirm_new_password_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(0, 10))
        
        self.change_password_button = ttk.Button(button_frame, text="确认修改", command=self.change_password, style='Primary.TButton')
        self.change_password_button.pack(side=tk.LEFT, padx=(0, 10), fill=tk.X, expand=True)
        
        self.cancel_change_password_button = ttk.Button(button_frame, text="取消", command=self.cancel_change_password)
        self.cancel_change_password_button.pack(side=tk.LEFT, fill=tk.X, expand=True)
    
    def change_password(self):
        # 验证输入
        old_password = self.old_password_entry.get().strip()
        new_password = self.new_password_entry.get().strip()
        confirm_new_password = self.confirm_new_password_entry.get().strip()
        
        # 检查是否为空
        if not old_password or not new_password or not confirm_new_password:
            messagebox.showerror("错误", "请输入所有密码字段！")
            return
        
        # 检查新密码是否一致
        if new_password != confirm_new_password:
            messagebox.showerror("错误", "两次输入的新密码不一致！")
            return
        
        # 验证旧密码是否正确
        if not self.verify_user("admin", old_password):
            messagebox.showerror("错误", "旧密码不正确！")
            return
        
        # 更新密码
        try:
            conn = sqlite3.connect('water_electricity.db')
            cursor = conn.cursor()
            cursor.execute("UPDATE users SET password=? WHERE username='admin'", (new_password,))
            conn.commit()
            conn.close()
            
            messagebox.showinfo("成功", "管理员密码修改成功！")
            self.cancel_change_password()
        except Exception as e:
            messagebox.showerror("错误", f"修改密码失败：{str(e)}")
    
    def cancel_change_password(self):
        # 关闭修改密码窗口
        self.change_password_window.destroy()